package sparseArray;
//稀疏数组
public class SparseArray {
    public static void main(String[] args) {
        //创建二维数组
        int chessArr1[][] = new int[11][11];
        //设置值
        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;
        //打印
        System.out.println();
        for (int[] arr : chessArr1) {
            for (int data : arr) {
                System.out.printf("%d\t", data);
            }
            System.out.print("\n");
        }
        //将二维数组转为稀疏数组：行不确定，列有3列
        int num = 0;//非0数据的个数
        for (int[] arr : chessArr1) {
            for (int data : arr) {
                if (data != 0) {
                    num++;
                }
            }
        }
        System.out.println();
        System.out.println("num =" + num);
        int height = chessArr1.length;
        int weight = chessArr1[0].length;
        //设置第一行
        int sparseArr[][] = new int[++num][3];
        sparseArr[0][0] = height;//二维数组的行
        sparseArr[0][1] = weight;//二维数组的列
        sparseArr[0][2] = num;//二维数组的非0数据数量
        //设置数据位置
        int count = 1;
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < weight; j++) {
                if (chessArr1[i][j] != 0){
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = chessArr1[i][j];
                    count++;
                }
            }
        }
        //打印稀疏数组
        System.out.println();
        for (int i = 0; i < sparseArr.length; i++) {
            for (int j = 0; j < sparseArr[0].length; j++) {
                System.out.printf("%d\t",sparseArr[i][j]);
            }
            System.out.println();
        }
        //稀疏数组转为二维数组
        int chessArr2[][] = new int[sparseArr[0][0]][sparseArr[0][1]];
        for (int i = 1; i < sparseArr.length; i++) {
                chessArr2 [sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];

        }
        //打印
        System.out.println();
        for (int[] arr : chessArr2) {
            for (int data : arr) {
                System.out.printf("%d\t", data);
            }
            System.out.print("\n");
        }
    }
}
